//
//  PlainViewController.m
//  EasyToo
//
//  Created by hydb on 13-6-10.
//
//

#import "PlainViewController.h"
#import "SegmenViewController.h"
#import "TSLocateView.h"

#define TFSTARTCITYTAG 100003

@interface PlainViewController ()

@end

@implementation PlainViewController
{
    UIAlertView *_baseAlert;
    
    UIImageView *_cityimgview;
    UILabel *_citylb;
    
    UITextField *_startCityTF;
    TSLocateView *_startLoc;
    
    UITextField *_arriveCityTF;
    TSLocateView *_arriveLoc;
    
    UIImageView *_dateimgview;
    UILabel *_datelb;
    
    UITextField *_dateTF;
    UIDatePicker *_datePicker;
    NSLocale *_datelocale;

    UIButton *_queryBtn;
    
    UIToolbar *_toolBar;
    UIBarButtonItem *_right;
    
    NSMutableArray *_cityList;
    NSMutableArray *_codeList;
    
    NSString *_StartIATACode;
    NSString *_ArriveIATACode;
    
    UIPickerView *_startCityPicker;
    UIPickerView *_arriveCityPicker;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //初始化视图
    _StartIATACode = [[NSString alloc] init];
    _ArriveIATACode = [[NSString alloc] init];
    
    _cityList = [[NSMutableArray alloc]init];
    _codeList = [[NSMutableArray alloc]init];
    
    //解析地址XML
    NSString *path=[[NSBundle mainBundle] pathForResource:@"airports" ofType:@"xml"];
    NSString *_xmlContent=[[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSXMLParser *parse=[[NSXMLParser alloc] initWithData:[_xmlContent dataUsingEncoding:NSUTF8StringEncoding]];
    [parse setDelegate:self];
    [parse parse];
    [parse release];

    [self init_view];
}

- (void)dealloc
{
    [_baseAlert release];
    [_cityimgview release];
    [_citylb release];
    [_startCityTF release];
    [_startLoc release];
    [_arriveCityTF release];
    [_arriveLoc release];
    [_dateimgview release];
    [_datelb release];
    [_dateTF release];
    [_datePicker release];
    [_datelocale release];
    [_queryBtn release];
    [_toolBar release];
    [_right release];
    [_cityList release];
    [_codeList release];
    [_StartIATACode release];
    [_ArriveIATACode release];
    [_startCityPicker release];
    [_arriveCityPicker release];
    
    
    _baseAlert = nil;
    _cityimgview = nil;
    _citylb = nil;
    _startCityTF = nil;
    _startLoc = nil;
    _arriveCityTF = nil;
    _arriveLoc = nil;
    _dateimgview = nil;
    _datelb = nil;
    _dateTF = nil;
    _datePicker = nil;
    _datelocale = nil;
    _queryBtn = nil;
    _toolBar = nil;
    _right = nil;
    _cityList = nil;
    _codeList = nil;
    _StartIATACode = nil;
    _ArriveIATACode = nil;
    _startCityPicker = nil;
    _arriveCityPicker = nil;
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




//初始化视图
- (void)init_view
{
    //定义title
    self.title = @"机票";
    //加载背影
     [self.view setBackgroundColor:BackgroundColor];
    
    
    int width = [DeviceUtil getScreenWidth];
    int heigth = self.view.frame.size.height;
    
    UIScrollView *myscrollview = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, heigth)]autorelease];
    myscrollview.directionalLockEnabled = YES; //只能一个方向滑动
    myscrollview.pagingEnabled = NO; //是否翻页
    myscrollview.backgroundColor = BackgroundColor;
    myscrollview.showsVerticalScrollIndicator =YES; //垂直方向的滚动指示
    myscrollview.indicatorStyle = UIScrollViewIndicatorStyleWhite;//滚动指示的风格
    myscrollview.showsHorizontalScrollIndicator = NO;//水平方向的滚动指示
    myscrollview.delegate = self;
    CGSize newSize = CGSizeMake(width, 1000);
    [myscrollview setContentSize:newSize];
    
    UIControl *control = [[[UIControl alloc] initWithFrame:myscrollview.frame] autorelease];
    [myscrollview addSubview:control];
    [control addTarget:self action:@selector(onBackgroudTouch) forControlEvents:UIControlEventTouchDown];
    

    
    
    //选择出行城市
    _cityimgview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"flight_03"]];
    _cityimgview.frame = CGRectMake(20, 20, 20, 20);
    [myscrollview addSubview:_cityimgview];
    
    _citylb = [[UILabel alloc]initWithFrame:CGRectMake(50, 20, 280, 20)];
    _citylb.text = @"选择出行城市";
    _citylb.font = [UIFont systemFontOfSize:15];
    _citylb.backgroundColor = [UIColor clearColor];
    _citylb.adjustsFontSizeToFitWidth = YES;
    [myscrollview addSubview:_citylb];
    
    //出发城市
    [self init_view_startcity:myscrollview];
    
    //出发城市
    [self init_view_arrivecity:myscrollview];
    
    //选择出行时间
    _dateimgview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"time_03"]];
    _dateimgview.frame = CGRectMake(20, 170, 20, 20);
    [myscrollview addSubview:_dateimgview];
    
    _datelb = [[UILabel alloc]initWithFrame:CGRectMake(50, 170, 280, 20)];
    _datelb.text = @"选择出行时间";
    _datelb.font = [UIFont systemFontOfSize:15];
    _datelb.backgroundColor = [UIColor clearColor];
    _datelb.adjustsFontSizeToFitWidth = YES;
    [myscrollview addSubview:_datelb];
    
    //起飞日期
    [self init_view_date:myscrollview];
    
    //查询
    _queryBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    _queryBtn.frame = CGRectMake(20, 260, 280, 40);
    [_queryBtn setBackgroundImage:[UIImage imageNamed:@"xyb"] forState:UIControlStateNormal];
    [_queryBtn setTitle:@"下一步" forState:UIControlStateNormal];
    _queryBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _queryBtn.layer.borderColor = [UIColor grayColor].CGColor;
    _queryBtn.layer.borderWidth = 1 ;
    _queryBtn.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_queryBtn];
    
    //添加button方法
    [_queryBtn addTarget:self action:@selector(queryEvent) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:myscrollview];

}

//出发城市
- (void)init_view_startcity:(UIScrollView*)myscrollview
{
//    _startCityTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 50, 280, 50)];
//    _startCityTF.text = @"";
//    _startCityTF.placeholder = @"出发城市";
//    _startCityTF.backgroundColor = [UIColor whiteColor];
//    
//    _startLoc = [[TSLocateView alloc] initWithTitle:@"出发城市" delegate:self];
//    _startLoc.tag = TFSTARTCITYTAG;
//    _startCityTF.inputView = _startLoc;
//    _startCityTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
//    _startCityTF.textColor = [UIColor blackColor];
//    _startCityTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//    _startCityTF.borderStyle = UITextBorderStyleRoundedRect;
//    _startCityTF.delegate = self ;
//    _startCityTF.returnKeyType =UIReturnKeyDone;
//    _startCityTF.layer.borderColor = [UIColor grayColor].CGColor;
//    _startCityTF.layer.borderWidth = 1 ;
//    _startCityTF.layer.cornerRadius = 10 ;
//    [myscrollview addSubview:_startCityTF];
    
    _startCityTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 50, 280, 50)];
    _startCityTF.tag = TFSTARTCITYTAG;
    _startCityTF.text = @"";
    _startCityTF.placeholder = @"出发城市";
    _startCityTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _startCityTF.textColor = [UIColor blackColor];
    _startCityTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _startCityTF.borderStyle = UITextBorderStyleRoundedRect;
    _startCityTF.delegate = self ;
    _startCityTF.returnKeyType =UIReturnKeyDone;
    _startCityTF.layer.borderColor = [UIColor grayColor].CGColor;
    _startCityTF.layer.borderWidth = 1 ;
    _startCityTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_startCityTF];
    
    // 建立 UIToolbar
    _toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    _right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelstartPicker)];
    
    // 把按鈕加進 UIToolbar
    _toolBar.items = [NSArray arrayWithObject:_right];
    
    _startCityPicker = [[UIPickerView alloc]initWithFrame:CGRectZero];
    _startCityPicker.showsSelectionIndicator = YES;
    
    _startCityTF.inputAccessoryView = _toolBar;
    _startCityTF.delegate = self;
    _startCityPicker.delegate = self;
    _startCityPicker.dataSource = self;
    _startCityPicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _startCityTF.inputView = _startCityPicker;
}

//到达城市
- (void)init_view_arrivecity:(UIScrollView*)myscrollview
{
//    _arriveCityTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 110, 280, 50)];
//    [_arriveCityTF setBorderStyle:UITextBorderStyleBezel];
//    _arriveCityTF.text = @"";
//    _arriveCityTF.placeholder = @"到达城市";
//    _arriveCityTF.backgroundColor = [UIColor whiteColor];
//    
//    _arriveLoc = [[TSLocateView alloc] initWithTitle:@"到达城市" delegate:self];
//    _arriveLoc.tag = TFARRIVECITYTAG;
//    _arriveCityTF.inputView = _arriveLoc;
//    _arriveCityTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
//    _arriveCityTF.textColor = [UIColor blackColor];
//    _arriveCityTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//    _arriveCityTF.borderStyle = UITextBorderStyleRoundedRect;
//    _arriveCityTF.delegate = self ;
//    _arriveCityTF.returnKeyType =UIReturnKeyDone;
//    _arriveCityTF.layer.borderColor = [UIColor grayColor].CGColor;
//    _arriveCityTF.layer.borderWidth = 1 ;
//    _arriveCityTF.layer.cornerRadius = 10 ;
//    [myscrollview addSubview:_arriveCityTF];
    
    _arriveCityTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 110, 280, 50)];
    _arriveCityTF.text = @"";
    _arriveCityTF.placeholder = @"到达城市";
    _arriveCityTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _arriveCityTF.textColor = [UIColor blackColor];
    _arriveCityTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _arriveCityTF.borderStyle = UITextBorderStyleRoundedRect;
    _arriveCityTF.delegate = self ;
    _arriveCityTF.returnKeyType =UIReturnKeyDone;
    _arriveCityTF.layer.borderColor = [UIColor grayColor].CGColor;
    _arriveCityTF.layer.borderWidth = 1 ;
    _arriveCityTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_arriveCityTF];
    
    // 建立 UIToolbar
    _toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    _right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelstartPicker)];
    
    // 把按鈕加進 UIToolbar
    _toolBar.items = [NSArray arrayWithObject:_right];
    
    _arriveCityPicker = [[UIPickerView alloc]initWithFrame:CGRectZero];
    _arriveCityPicker.showsSelectionIndicator = YES;
    
    _arriveCityTF.inputAccessoryView = _toolBar;
    _arriveCityTF.delegate = self;
    _arriveCityPicker.delegate = self;
    _arriveCityPicker.dataSource = self;
    _arriveCityPicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _arriveCityTF.inputView = _arriveCityPicker;
}

//出发日期
- (void)init_view_date:(UIScrollView*)myscollview
{
    _dateTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 200, 280, 50)];
    _dateTF.text = @"";
    _dateTF.placeholder = @"出发日期";
    _dateTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _dateTF.textColor = [UIColor blackColor];
    _dateTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _dateTF.borderStyle = UITextBorderStyleRoundedRect;
    _dateTF.delegate = self ;
    _dateTF.returnKeyType =UIReturnKeyDone;
    _dateTF.layer.borderColor = [UIColor grayColor].CGColor;
    _dateTF.layer.borderWidth = 1 ;
    _dateTF.layer.cornerRadius = 10 ;
    [myscollview addSubview:_dateTF];
    
    // 建立 UIDatePicker
    _datePicker = [[UIDatePicker alloc]init];
    
    // 時區的問題請再找其他協助 不是本篇重點
    _datelocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_TW"];
    _datePicker.locale = _datelocale;
    _datePicker.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    
    // 以下這行是重點 (螢光筆畫兩行) 將 UITextField 的 inputView 設定成 UIDatePicker
    // 則原本會跳出鍵盤的地方 就改成選日期了
    _dateTF.inputView = _datePicker;
    
    // 建立 UIToolbar
    _toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 420, 44)];
    
    // 選取日期完成鈕 並給他一個 selector
    _right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelPicker)];
    
    // 把按鈕加進 UIToolbar
    _toolBar.items = [NSArray arrayWithObject:_right];
    
    // 以下這行也是重點 (螢光筆畫兩行)
    // 原本應該是鍵盤上方附帶內容的區塊 改成一個 UIToolbar 並加上完成鈕
    _dateTF.inputAccessoryView = _toolBar;
}



//查询事件
- (void)queryEvent
{
    //检测用户名密码是否为空
    if ([_startCityTF.text isEqualToString:@""] == YES || [_arriveCityTF.text isEqualToString:@""] == YES) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"数据为空" message:@"城市和日期不能为空"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    else if ([_startCityTF.text isEqualToString:_arriveCityTF.text])
    {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"数据错误" message:@"出发城市和到达城市不能相同"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    //转发请求
    else{
        for (int i = 0; i < [_cityList count]; i++) {
            NSString *cityname = [_cityList objectAtIndex:i];
            if ([_startCityTF.text isEqualToString:cityname]) {
                _StartIATACode = [_codeList objectAtIndex:i];
            }
            else if ([_arriveCityTF.text isEqualToString:cityname]){
                _ArriveIATACode = [_codeList objectAtIndex:i];
            }
        }
        
        SegmenViewController *segmentController = [[SegmenViewController alloc] init];
        segmentController.startCity = _startCityTF.text;
        segmentController.arriveCity = _arriveCityTF.text;
        segmentController.startCityCode = _StartIATACode;
        segmentController.arriveCityCode = _ArriveIATACode;
        segmentController.startDate = _dateTF.text;
        [self.navigationController pushViewController:segmentController animated:YES];
        [segmentController release];
    }
    
}

- (void) performDismiss: (NSTimer *)timer {
    [_baseAlert dismissWithClickedButtonIndex:0 animated:NO];//important
    [_baseAlert release];
    _baseAlert = NULL;
}



#pragma picker delegate
-(void) cancelstartPicker {
    [_startCityTF endEditing:YES];
    [_arriveCityTF endEditing:YES];
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [_cityList count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [_cityList objectAtIndex:row];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[[UILabel alloc] init] autorelease];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont systemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == TFSTARTCITYTAG) {
        NSInteger row = [_startCityPicker selectedRowInComponent:0];
        _startCityTF.text = [_cityList objectAtIndex:row];
    } else {
        NSInteger row = [_arriveCityPicker selectedRowInComponent:0];
        _arriveCityTF.text = [_cityList objectAtIndex:row];
    }
    
}




#pragma date picker delegate
// 按下完成鈕後的 method
-(void) cancelPicker {
    // endEditing: 是結束編輯狀態的 method
    if ([self.view endEditing:NO]) {
        // 以下幾行是測試用 可以依照自己的需求增減屬性
        NSDateFormatter *formatter = [[[NSDateFormatter alloc] init]autorelease];
        NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"yyyy-MM-dd" options:0 locale:_datelocale];
        [formatter setDateFormat:dateFormat];
        [formatter setLocale:_datelocale];
        // 將選取後的日期 填入 UITextField
        _dateTF.text = [NSString stringWithFormat:@"%@",[formatter stringFromDate:_datePicker.date]];
    }
}


#pragma mark UITextFieldDelegate
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_dateTF resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)onBackgroudTouch
{
    [_dateTF resignFirstResponder];
}

#pragma mark actionsheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    TSLocateView *locateView = (TSLocateView *)actionSheet;
    TSLocation *location = locateView.locate;
//    NSLog(@"city:%@ lat:%f lon:%f", location.city, location.latitude, location.longitude);
    if(buttonIndex != 0) {
        if (locateView.tag == TFSTARTCITYTAG) {
            _startCityTF.text = location.city;
        } else {
            _arriveCityTF.text = location.city;
        }
    }
}


#pragma xmlparse
//第一个代理方法：
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    //判断是否是meeting
    if ([elementName isEqualToString:@"list"]) {
        
        //判断属性节点
        if ([attributeDict objectForKey:@"SCName"]) {
            //获取属性节点中的值
            [_cityList addObject:[attributeDict objectForKey:@"SCName"]];
            [_codeList addObject:[attributeDict objectForKey:@"IATACode"]];
            
        }
    
    }
}


@end



